//
//  WHYPhotoBeowerViewController.swift
//  WHYWeibo-1.0
//
//  Created by 王洪运 on 15/12/2.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit
import SVProgressHUD

private let WHYPhotoBrowserViewCellID = "WHYWBPhotoBrowserViewCellID"

class WHYPhotoBrowserViewController: UIViewController {

/// 图片地址数组
    var urls: [NSURL]
/// 选中图片索引
    var selectedIndexPath: NSIndexPath
    
//    MARK: - 监听事件
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func save() {
        
        guard let image = (collectionView.visibleCells().last as? WHYPhotoBrowserCell)?.imageView.image else {
            QL4("没有图像")
            return
        }
        
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    @objc private func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
        
        let message = (error != nil) ? "保存失败" : "保存成功"
        
        SVProgressHUD.showInfoWithStatus(message)
        
    }
    
//    MARK: - 视图生命周期函数
    override func loadView() {
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20//使根视图比屏幕宽20
        
        view = UIView(frame: rect)
        
        setupUI()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
//        var onceToken: dispatch_once_t
//        dispatch_once(onceToken) { () -> Void in
//            
//        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        显示选中的图片
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: .CenteredHorizontally, animated: false)
    }
    
//    MARK: - 构造函数
    init(urls: [NSURL], selectedIndexPath: NSIndexPath) {
        self.urls = urls
        self.selectedIndexPath = selectedIndexPath
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK: - 懒加载子控件
    lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: WHYPhotoBrowserFlowLayout())
    
    private lazy var closeButton: UIButton = UIButton(title: "关闭",
        titleColor: UIColor.whiteColor(),
        fontSize: 14,
        imageName: nil,
        backgroundColor: UIColor.darkGrayColor())
    
    private lazy var saveButton: UIButton = UIButton(title: "保存",
        titleColor: UIColor.whiteColor(),
        fontSize: 14,
        imageName: nil,
        backgroundColor: UIColor.darkGrayColor())

}

// MARK: - WHYPhotoBrowserDismissDelegate
extension WHYPhotoBrowserViewController: WHYPhotoBrowserDismissDelegate {
    
    func imageViewForDismiss() -> UIImageView {
        let imageView = UIImageView()
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        
        let cell = collectionView.visibleCells().first as! WHYPhotoBrowserCell
        
        imageView.image = cell.imageView.image
        imageView.frame = cell.scrollView.convertRect(cell.imageView.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        return imageView
    }
    
    func indexPathForDismiss() -> NSIndexPath {
        return collectionView.indexPathsForVisibleItems().first!
    }
    
}

// MARK: - setupUI
extension WHYPhotoBrowserViewController {
    
    private func setupUI () {
        
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        collectionView.frame = view.bounds
        
        let margin = 8
        let width: CGFloat = 100
        let height: CGFloat = 36
        
        closeButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(-margin)
            make.left.equalTo(view).offset(margin)
            make.size.equalTo(CGSize(width: width, height: height))
        }
        
        saveButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(-margin)
            make.right.equalTo(view).offset(-28)
            make.size.equalTo(CGSize(width: width, height: height))
        }
        
        closeButton.addTarget(self, action: "close", forControlEvents: .TouchUpInside)
        saveButton.addTarget(self, action: "save", forControlEvents: .TouchUpInside)
        
        prepareCollectionView()
    }
    
    private func prepareCollectionView () {
        
        collectionView.registerClass(WHYPhotoBrowserCell.self, forCellWithReuseIdentifier: WHYPhotoBrowserViewCellID)
        
        collectionView.dataSource = self
        
    }
    
}

// MARK: - UICollectionViewDataSource
extension WHYPhotoBrowserViewController: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WHYPhotoBrowserViewCellID, forIndexPath: indexPath) as! WHYPhotoBrowserCell
        
        cell.imageURL = urls[indexPath.item]
        cell.delegate = self
        
        return cell
    }
    
}

// MARK: - WHYPhotoBrowserCellDelegate
extension WHYPhotoBrowserViewController: WHYPhotoBrowserCellDelegate {
    
    func photoBrowserCellShouldDismiss() {
        close()
    }
    
    func photoBrowserCellDidZoom(scale: CGFloat) {
        
        let startInteraction = scale < 1.0
        
        hiddenController(startInteraction)
        
        if startInteraction {
            view.alpha = scale
            view.transform = CGAffineTransformMakeScale(scale, scale)
        }else {
            view.alpha = 1.0
            view.transform = CGAffineTransformIdentity
        }
        
    }
    
    private func hiddenController(isHidden: Bool) {
        closeButton.hidden = isHidden
        saveButton.hidden = isHidden
        
        collectionView.backgroundColor = isHidden ? UIColor.clearColor() : UIColor.blackColor()
    }
    
}

// MARK: - WHYPhotoBrowserFlowLayout
private class WHYPhotoBrowserFlowLayout: UICollectionViewFlowLayout {
    
    private override func prepareLayout() {
        super.prepareLayout()
        
        itemSize = collectionView!.bounds.size
        
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        
        scrollDirection = .Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
    }
    
}












